import 'package:fig/models/media.dart';
import 'package:fig/sqlite/sql_manager.dart';
import 'package:fig/sqlite/table_media_actor.dart';
import 'package:fig/sqlite/table_media_area.dart';
import 'package:fig/sqlite/table_media_category.dart';
import 'package:fig/sqlite/table_media_lang.dart';
import 'package:sqflite_common/sqlite_api.dart';

class TableMedia extends TableBase {
  // 表名
  final String tableName = 'media';

  static final String columnOriginId = "origin_id"; // 第三方的ID
  static final String columnName = "name";
  static final String columnSubName = "sub_name";
  static final String columnCover = "cover";
  static final String columnDescription = "description";
  static final String columnDoubanRank = "douban_rank";
  static final String columnUpNum = "up_num";
  static final String columnDownNum = "down_num";
  static final String columnDirector = "director";
  static final String columnActor = "actor";
  static final String columnTag = "tag";
  static final String columnYear = "year";
  static final String columnArea = "area";
  static final String columnLang = "lang";
  static final String columnPubDate = "pub_date";
  static final String columnImdb = "imdb";
  static final String columnPlayData = "play_data";

  TableMedia(); // 匿名构造函数

  Future<List<Media>> pageByCategory(int category, int page, int pageSize) async {
    Database db = await SqlManager.getCurrentDatabase();

    String sql = '''select Media.* from $tableName Media
     left join ${TableMediaCategoryMap.tableName} Map on Map.${TableMediaCategoryMap.columnMediaId}=Media.${TableBase.columnId}
     where Map.${TableMediaCategoryMap.columnCategoryId}=$category
      limit $pageSize offset ${(page - 1) * pageSize}''';
    // print('pageByCategory:$sql');
    var medias = await db.rawQuery(sql);
    return medias.map((mediaMap) => Media.fromMap(mediaMap)).toList();
  }

  // 插入或更新影视数据
  Future<void> initMedias(List<dynamic> jsonList) async {
    Database db = await SqlManager.getCurrentDatabase();
    for (Map<String, dynamic> jsonMedia in jsonList) {
      Media media = Media.fromGeneralSpiderJson(jsonMedia);

      bool existed = await insert(db, media);
      if (existed) {
        continue;
      }

      // 处理导演、演员、语言、地域等信息
      TableMediaCategory().insertMap(media.id, media.categoryId, database: db);
      TableMediaActor().insertAllWithMediaId(media.id, media.actor, 0, database: db);
      TableMediaActor().insertAllWithMediaId(media.id, media.director, 1, database: db);
      TableMediaArea().insertAllWithMediaId(media.id, media.area, database: db);
      TableMediaLang().insertAllWithMediaId(media.id, media.lang, database: db);
      // TableMediaTag().installAllWithMediaId(media.id, media.tag);

      print(media.toMap());
    }
  }

  // 插入，并返回是否已存在该数据
  Future<bool> insert(Database db, Media media) async {
    media.fix();
    var existMediaList = await db.query(tableName, where: '$columnOriginId=?', whereArgs: [media.originId], limit: 1);
    if (existMediaList.length > 0) {
      // print('已存在的影视:${media.name}');
      return true;
    }

    var insertedId = await db.insert(tableName, media.toMap());
    media.id = insertedId;
    print('影视:${media.name} 插入成功，对应的ID:$insertedId');
    return false;
  }

  @override
  createTable(Database db) {
    db.execute('''create table $tableName (
    ${TableBase.columnId} integer PRIMARY KEY AUTOINCREMENT NOT NULL,
    $columnOriginId integer NOT NULL UNIQUE,
    $columnName text,
    $columnSubName text,
    $columnCover text,
    $columnDescription text,
    $columnDoubanRank integer,
    $columnUpNum integer,
    $columnDownNum integer,
    $columnDirector text,
    $columnActor text,
    $columnTag text,
    $columnYear integer,
    $columnArea text,
    $columnLang text,
    $columnPubDate integer,
    $columnImdb text,
    $columnPlayData text,
    ${TableBase.columnCreateTime} integer
    )''');
  }
}
